#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    signArray << "+" << "-" << "*";
    ui->label->setAlignment(Qt::AlignRight);
    this->register_Btn_Cls();
    sendsomething = new SendObj;
    op = new Operate;
    connect(sendsomething, SIGNAL(send(QPushButton*,QLabel*)), op, SLOT(print(QPushButton*,QLabel*)), Qt::QueuedConnection);
    connect(sendsomething, SIGNAL(send(QPushButton*,QLabel*,QLCDNumber*)), op, SLOT(print(QPushButton*,QLabel*,QLCDNumber*)), Qt::QueuedConnection);
    connect(sendsomething, SIGNAL(send(QLabel*,QString)), op, SLOT(print(QLabel*,QString)), Qt::QueuedConnection);

    connect(sendsomething, SIGNAL(toClear(QLabel*,QLCDNumber*)), op, SLOT(clear(QLabel*,QLCDNumber*)), Qt::QueuedConnection);
    connect(sendsomething, SIGNAL(toDel(QLabel*)), op, SLOT(del(QLabel*)), Qt::QueuedConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::sendSlot(){
    myButton = (QPushButton*) sender();
    if(signArray.contains(myButton->text())){
        emit sendsomething->send(ui->label, myButton->text());
    }else if(myButton->text() == "="){
        emit sendsomething->send(myButton, ui->label, ui->lcdNumber);
    }else if (myButton->text() == "AC") {
        emit sendsomething->toClear(ui->label, ui->lcdNumber);
    }else if (myButton->text() == "<-") {
        emit sendsomething->toDel(ui->label);
    }else{
        emit sendsomething->send(myButton, ui->label);
    }
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event){  // 事件过滤器，拦截按钮被点击的事件
    if(event->type()==QEvent::MouseButtonPress){
        btnCls = (QPushButton*)obj;
        qDebug() << obj << btnCls << event->type();
        connect(btnCls, &QPushButton::clicked, this, &MainWindow::sendSlot, Qt::UniqueConnection);
        return false;
    }
    return QMainWindow::eventFilter(obj, event);
}

void MainWindow::register_Btn_Cls(){  // 给按钮对象注册事件过滤器
    ui->B_0->installEventFilter(this);
    ui->B_1->installEventFilter(this);
    ui->B_2->installEventFilter(this);
    ui->B_3->installEventFilter(this);
    ui->B_4->installEventFilter(this);
    ui->B_5->installEventFilter(this);
    ui->B_6->installEventFilter(this);
    ui->B_7->installEventFilter(this);
    ui->B_8->installEventFilter(this);
    ui->B_9->installEventFilter(this);
    ui->B_Plus->installEventFilter(this);
    ui->B_Mul->installEventFilter(this);
    ui->B_Sub->installEventFilter(this);
    ui->B_AC->installEventFilter(this);
    ui->B_Del->installEventFilter(this);
    ui->B_Eq->installEventFilter(this);
}
